package com.gvsoft.communication.common;

import com.gvsoft.communication.console.Console;
import com.gvsoft.communication.console.IControl;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * ProjectName:MService
 * Author: zhaoqiubo
 * Date: 15/11/24
 * Time: 上午9:24
 * Desc: 配置抽象类
 */
public abstract class Config {

    private final static Logger logger = LogManager.getLogger("net");


    /**
     * 网络报文读取缓冲区大小
     */
    private static Integer readBlock = 8192;
    /**
     * 读包buffer缓冲区默认大小
     */
    private static Integer readBufferPoolSize = 1000;

    /**
     * 管理端口
     */
    private static int consolePort = 9091;

    public static int getConsolePort() {
        return consolePort;
    }

    public static Integer getReadBlock() {
        return readBlock;
    }

    public static Integer getReadBufferPoolSize() {
        return readBufferPoolSize;
    }

    /**
     * 初始化控制器实例池
     * @param consoleStr 控制器的配置字符串
     */
    protected static void initController(String consoleStr) {
        String[] handleOuterArray = Tools.str2ArrayByChar(consoleStr, "|");
        try {
            for (String handleOuterStr : handleOuterArray) {
                String[] handleInnerArray = Tools.str2ArrayByChar(handleOuterStr, ":");
                Class c = Class.forName(handleInnerArray[1]);
                Object controllerClass = c.newInstance();
                Console.regCmd(handleInnerArray[0], (IControl) controllerClass);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载全局配置
     *
     * @param commonCfgFile 配置文件路径
     * @return 是否成功
     */
    public static boolean initCommonCfg(String commonCfgFile) {
        InputStreamReader reader = null;
        try {
            reader = new InputStreamReader(new FileInputStream
                    (commonCfgFile), "utf-8");

            Properties commonP = new Properties();
            commonP.load(reader);
            consolePort = Integer.parseInt(commonP.getProperty("console_port").trim());
            readBufferPoolSize = Integer.parseInt(commonP.getProperty("read_buffer_pool_size").trim());
            readBlock = Integer.parseInt(commonP.getProperty("read_block").trim());
            initController(commonP.getProperty("console_class"));
            return true;
        } catch (IOException e) {
            logger.error("Failed to initialize the common configuration parameter！reason:" + e.getMessage());
            return false;
        } finally {
            try {
                if (reader!=null) {
                    reader.close();
                }
            } catch (IOException e) {
                logger.error("Failed to close the InputStreamReader ！reason:" + e.getMessage());
            }
        }
    }
}
